<template>
  <div class="QRcodeList-qrcanvas-increase">
      <a-modal v-model:visible="visibleQRQrCode" title="会议签名二维码汇总" width="80%" wrapClassName="QRcodeList-qrcanvas-increase-modal">
          <a-spin size="large" :spinning="spinning">
            <div>
              <a-button class="blue-btn" type="primary" @click="" v-print="printObj" style="margin-right: 10px;">打印</a-button>
              <a-button class="blue-btn" type="primary" @click="onSaveCanvas">下载</a-button>
            </div>
            <div style="max-height: calc(100vh - 350px);overflow-y: scroll;">
                <div id="printTest" v-if="visibleQRQrCode">
                    <h2 style="text-align: center;">{{hyzt}}</h2>
                    <div class="codelist-box">
                        <div v-for="(item,index) in codeList" :key="index" style="display: inline-block;">
                        <canvas :key="canvasKey + item.id" :id="canvasId + item.id" width="206px" height="190px"></canvas>
                        </div>
                    </div>
                </div>
            </div>
          </a-spin>
          <template slot="footer">
            <a-button class="blue-btn" @click="visibleQRQrCode = false">
                关闭
            </a-button>
        </template>
      </a-modal>
  </div>
</template>
<script>
import {qrcanvas} from 'qrcanvas'
import html2canvas from "html2canvas";
export default {
  components:{
  },
  props:{
      id:{
          type:String,
          default:'',
          require:false
      }
  },
  data(){
      return{
          spinning:true,
          visibleQRQrCode:false,
          testPaper:{},
          newImage:new Image(),
          queryResultsQr:null,
          queryResultsImgUrl:'',
          canvasKey:null,
          canvasId:'signedVersion'+ new Date().getTime(),
          canvasIdList: [],
          codeList: [],
          hyzt: '',
          // 打印
          printObj:{
            id:"printTest", //需要打印的id名称
            popTitle:"会议签名二维码汇总表",//文档的名称
            // preview:true,//预览功能，不好用
            zIndex:'20002',
            beforeOpenCallback(vue){},
            openCallback (vue) {
              //打开之前
            },
            closeCallback (vue) {
              //关闭了打印工具
            },
          },
      }
  },
  watch:{
      visibleQRQrCode(newval,oldVal){
          this.spinning = true
          // if(newval){
          //     this.queryResultsQr = qrcanvas({
          //         data: bootConfig[process.env.NODE_ENV].EXTERNAL_ACCESS_URL+`/t_yjjspzx/questionnaireInvestigate?id=`+this.id   || "二维码生成中",
          //         size:260,
          //         background:'#fff'
          //     })
          //     this.queryResultsImgUrl = this.newImage.src = this.queryResultsQr.toDataURL("image/png")
          // }
      },


  },
  mounted(){

  },
  updated(){
      this.cancelLoading()
  },
  methods:{
      getData(val,zt){
        this.codeList = val
        this.hyzt = zt
        //console.log('this.codeList',this.codeList)
        this.codeList.forEach((item,index) => {
          let queryResultsQr = ''
          queryResultsQr = qrcanvas({
              data: bootConfig[process.env.NODE_ENV].EXTERNAL_ACCESS_URL2+process.env.BASE_URL+`onSiteInspectionCheckInSignedVersion?id=`+item.id|| "二维码生成中",
              size:260,
              background:'#fff'
          })
          this.queryResultsImgUrl = this.newImage.src = queryResultsQr.toDataURL("image/png")
          this.canvasKey = Date.now()
          //console.log('111')
          this.$nextTick(()=>{
              var canvas = document.getElementById(this.canvasId + item.id);
              var context = canvas.getContext('2d');
              context.font = "18px Arial"
              context.textAlign = "center"
              // context.globalCompositeOperation = 'source-in';
              context.fillStyle = "#000";
              context.background = '#fff'
              context.fillText(item.fxm + '会议签名',118,160);
              var img = new Image();
              img.onload = function() {
                  context.drawImage(img, 53, 10,130,130);
              }
              img.src = queryResultsQr.toDataURL("image/png");
            })
        })
      },
      cancelLoading(){
          let timer = setInterval((val)=>{
              this.spinning = false
              clearInterval(timer);
          },500)
      },
      downloadQRCode(val){
            var canvas = document.getElementById('printTest');
            var dataURL = canvas.toDataURL('image/png');
            // 创建一个链接元素
            var link = document.createElement('a');
            link.download = this.hyzt + '会议签名二维码汇总表.png'; // 设置图片名称
            link.href = dataURL; // 设置图片链接
            link.click(); // 模拟点击链接，下载图片
        },
        //点击保存为Canvas
      onSaveCanvas() {
        // 这里的类名要与点击事件里的一样
        const canvas = document.querySelector("#printTest");
        let that = this;
        html2canvas(canvas, { scale: 2, logging: false, useCORS: true }).then(
          function (canvas) {
            const type = "png";
            let imgData = canvas.toDataURL(type);
            // 图片格式处理
            let _fixType = function (type) {
              type = type.toLowerCase().replace(/jpg/i, "jpeg");
              let r = type.match(/png|jpeg|bmp|gif/)[0];
              return "image/" + r;
            };
            imgData = imgData.replace(_fixType(type), "image/octet-stream");
            let filename = that.hyzt + "会议签名二维码汇总表" + "." + type;
            // 保存为文件
            //  以bolb文件下载
            that.downFileToLocal(filename, that.convertBase64ToBlob(imgData));
          }
        );
      },
      // base64转化为Blob对象
      convertBase64ToBlob(imageEditorBase64) {
        let base64Arr = imageEditorBase64.split(",");
        let imgtype = "";
        let base64String = "";
        if (base64Arr.length > 1) {
          //如果是图片base64，去掉头信息
          base64String = base64Arr[1];
          imgtype = base64Arr[0].substring(
            base64Arr[0].indexOf(":") + 1,
            base64Arr[0].indexOf(";")
          );
        }
        // 将base64解码
        let bytes = atob(base64String);
        //let bytes = base64;
        let bytesCode = new ArrayBuffer(bytes.length);
        // 转换为类型化数组
        let byteArray = new Uint8Array(bytesCode);

        // 将base64转换为ascii码
        for (let i = 0; i < bytes.length; i++) {
          byteArray[i] = bytes.charCodeAt(i);
        }
        // 生成Blob对象（文件对象）
        return new Blob([bytesCode], { type: imgtype });
      },
      // 下载Blob流文件
      downFileToLocal(fileName, blob) {
        // 创建用于下载文件的a标签
        const d = document.createElement("a");
        // 设置下载内容
        d.href = URL.createObjectURL(blob);
        // 设置下载文件的名字
        d.download = fileName;
        // 界面上隐藏该按钮
        d.style.display = "none";
        // 放到页面上
        document.body.appendChild(d);
        // 点击下载文件
        d.click();
        // 从页面移除掉
        document.body.removeChild(d);
        // 释放 URL.createObjectURL() 创建的 URL 对象
        window.URL.revokeObjectURL(d.href);
      },
  }

}

</script>
<style lang="less">
/* .ant-form-item-label{
  font-weight: 600;
} */
.ant-modal-title{
  font-weight: 600;
}
.ant-modal-header{
  background: #5ca3e5;
}
.ant-upload-list{
  display: none !important;
}
.test-paper-modal .ant-modal-footer{
  display: none !important;
}
.ant-modal-footer .ant-btn-primary{
  border: 1px solid #5ca3e5 !important;
  background-color: #5ca3e5 !important;
  color: #fff !important;
}
.paper-details{
  display: flex;
  flex-direction: column;
  text-align: center;
  font-size: 20px;
  font-weight: 600;
}
.qr-img-box{
  display: flex;
  justify-content: center;
}
.QRcodeList-qrcanvas-increase .ant-modal-content{
  width: 520px !important;
}
.QRcodeList-qrcanvas-increase-modal {
  .codelist-box {
    text-align: center;
  }
}
</style>
